package com.bodacn.keypoint;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.ksoap2.SoapFault;
import org.ksoap2.transport.HttpResponseException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bodacn on 2017/6/1.
 */

public class AutoUpdate {

    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath,applicationID;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;





    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    public AutoUpdate(Context context, String applicationID)
    {
        this.mContext = context;
        this.applicationID=applicationID;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context)
    {
        int versionCode = 0;

            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo(applicationID, 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }

        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog()
    {

        GuideActivity.NeedUpdate=true;
        System.out.println("对话框...............................1");
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("软件更新");
        builder.setMessage("检测到有新版本,立即更新？");
        System.out.println("对话框...............................2");
        // 更新
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
            }
        });
        builder.setCancelable(false);
        System.out.println("对话框...............................3");
        // 稍后更新
        /*
        builder.setNegativeButton("稍后更新", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        */
        System.out.println("准备显示.....");
        builder.create().show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog()
    {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(false);
        builder.setTitle("更新进程");
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 现在文件
        downloadApk();
    }

    //从网络获取版本升级文件
    public void CheckWebUpdate(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetWebUpdateFile","文件接收A:---"+serviceUrl);
                try {
                    ParseXmlService service = new ParseXmlService();
                    InputStream inStream = new URL(serviceUrl).openStream();
                    System.out.println("版本文件获取成功....");
                    mHashMap = service.parseXml(inStream);
                    System.out.println("版本文件解析成功....");
                    return "OK";
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d("msg","查询数据出错,错误异常抛出！");
                return "NO";
            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr==null)||(rtnstr=="NO"))
                {
                    Toast.makeText(mContext, "版本更新文件下载错误", Toast.LENGTH_LONG).show();
                    return;
                }
                //这部分主要用于UI更新;
                Log.d("msg","文件获取成功..");
                //判断版本是否相同;
                if (null != mHashMap)
                {
                    int serviceCode = Integer.valueOf(mHashMap.get("version"));
                    System.out.println("最新版本为"+serviceCode+"--------------------------------------------------");
                    // 版本判断
                    // 获取当前软件版本
                    int versionCode = getVersionCode(mContext);
                    System.out.println("当前版本为"+versionCode+"--------------------------------------------------");
                    if (serviceCode > versionCode)
                    {
                        System.out.println("准备显示升级提示对话框--------------------------------------------------");
                        // 显示提示对话框
                        showNoticeDialog();
                    } else
                    {
                        Toast.makeText(mContext, "版本已是最新版", Toast.LENGTH_LONG).show();
                    }
                }

            }
        }.execute(params);

    }

    /**
     * 下载apk文件
     */
    private void downloadApk()
    {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     *@date 2012-4-26
     *@blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                // 判断SD卡是否存在，并且是否具有读写权限
                String sdpath="";
                boolean sdCardExist =Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
                if (sdCardExist==true) {
                    System.out.println("下载过程.......................................0");
                    sdpath = Environment.getExternalStorageDirectory() + "/";
                    System.out.println("下载过程.......................................1");
                    mSavePath = sdpath + "download";
                    URL url = null;
                    try {
                        url = new URL(mHashMap.get("url"));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    System.out.println("下载过程.......................................2");
                    // 创建连接
                    HttpURLConnection conn = null;
                    try {
                        conn = (HttpURLConnection) url.openConnection();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("下载过程.......................................2.1");
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    File file = new File(mSavePath);
                    System.out.println("下载过程.......................................3:" + mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        System.out.println("下载过程.......................................3:建目录开始");
                        file.mkdir();
                        System.out.println("下载过程.......................................3:建目录完成");
                    }
                    File apkFile = new File(mSavePath, mHashMap.get("name"));
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    System.out.println("下载过程.......................................4");
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                        System.out.println("下载过程......................................."+count);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
                System.out.println(e.getMessage());
            } catch (IOException e)
            {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    };

    /**
     * 安装APK文件
     */
    private void installApk()
    {
        File apkfile = new File(mSavePath, mHashMap.get("name"));
        if (!apkfile.exists())
        {
            return;
        }
        // 通过Intent安装APK文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
